package demo.proxy;


import java.io.File;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : feixiang.li
 * @since : 2025-09-18 13:56
 */
public class MyInterfaceFactory {

    public static final AtomicInteger count = new AtomicInteger(1);

    public static final String PACKAGE_NAME = "com.lkcoffee.demo.proxy";

    public static File createFile(String className, MyHandler myHandler) throws Exception {


        String functionBody1 = myHandler.getBody("doSomething");
        String functionBody2 = myHandler.getBody("func1");
        String functionBody3 = myHandler.getBody("func2");

        String content = "package com.lkcoffee.demo.proxy;\n" + "public class " + className + " implements MyInterface {\n" + "    MyInterface my;" + "    @Override\n" + "    public void doSomething() {\n" + "        " + functionBody1 + ";\n" + "    }\n" + "\n" + "    @Override\n" + "    public void func1() {\n" + "       " + functionBody2 + ";\n" + "    }\n" + "\n" + "    @Override\n" + "    public void func2() {\n" + "        " + functionBody3 + ";\n" + "    }\n" + "}\n";
        File javaFile = new File(className + ".java");
        Files.writeString(javaFile.toPath(), content);
        return javaFile;
    }

    public static MyInterface newInnstance(String className, MyHandler myHandler) throws Exception {
        Class<?> clazz = MyInterfaceFactory.class.getClassLoader().loadClass(className);
        Constructor<?> constructor = clazz.getConstructor();
        MyInterface myInterface = (MyInterface) constructor.newInstance();
        myHandler.setProxy(myInterface);
        return myInterface;
    }


    public static String functionBody(String methodName) {
        return " System.out.println(\"" + methodName + "\")";
    }

    public static String getName() {
        return "MyNameInterface$proxy" + count.getAndIncrement();
    }


    public static MyInterface createProxy(MyHandler myHandler) throws Exception {
        String className = getName();
        File file = createFile(className, myHandler);
        Complier.compile(file);
        MyInterface proxy = newInnstance(PACKAGE_NAME + "." + className, myHandler);
        return proxy;
    }

    public static void main(String[] args) throws Exception {
    }
}
